<template>
  <div class="banner-add">
    <div class="createPost-main-container">
      <el-form ref="form" label-width="120px" :model="form">
        <div v-for="(item, idx) in basicItems" :key="idx">
          <el-card class="box-card logo-card">
            <div slot="header" class="clearfix">
              <span>序号：{{ idx + 1 }}</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="deletCard(idx)">删除</el-button>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                :disabled="idx === basicItems.length - 1"
                @click="moveDown(idx)"
              >下移</el-button>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                :disabled="idx === 0"
                @click="moveUp(idx)"
              >上移</el-button>
            </div>
            <div class="text item">
              <el-form-item label="挂载内容类型" required>
                <el-select v-model="item.linkType" filterable placeholder="挂载内容类型">
                  <el-option
                    v-for="(type, index) in typeList"
                    :key="index"
                    :label="type.text"
                    :value="type.value"
                  />
                </el-select>
              </el-form-item>
              <template v-if="item.linkType === 'news'">
                <el-form-item v-for="(type, _index) in activeTypeList('newsType')" :key="'newsType_'+_index" label="资讯类型">
                  <el-select v-model="item.newsType" filterable placeholder="资讯类型内容">
                    <el-option
                      v-for="(link, index) in links[type.ref]"
                      :key="'nt_'+index"
                      :label="link.name"
                      :value="link.id"
                    />
                  </el-select>
                </el-form-item>
              </template>
              <el-form-item v-for="(type, _index) in activeTypeList(item.linkType, item.newsType)" :key="'link'+_index" label="挂载内容">
                <el-select v-model="item.link" filterable placeholder="详情">
                  <el-option
                    v-for="(link, index) in links[type.ref]"
                    :key="index"
                    :label="link.name"
                    :value="link.id"
                  />
                </el-select>
              </el-form-item>
              <template v-if="item.linkType === 'newsType'" class="text item">
                <el-form-item label="资讯板块标题">
                  <el-input v-model="item.value" />
                </el-form-item>
              </template>
            </div>
            <div class="text item">
              <el-button @click="goToDetail(item)">点击去修改内容</el-button>
            </div>
          </el-card>
        </div>
        <el-button
          :loading="ajaxStatus"
          style="margin-left: 10px;"
          type="primary"
          plain
          @click="addCard"
        >
          增加
        </el-button>
      </el-form>
    </div>
    <sticky :class-name="'cms-sub-navbar '+ajaxStatus">
      <el-button :loading="ajaxStatus" style="margin-left: 10px;" type="success" @click="submitForm('up')">
        发布
      </el-button>
      <el-button :loading="ajaxStatus" @click="reset()">
        取消
      </el-button>
    </sticky>
    <el-dialog title="新增模块" :visible.sync="dialogFormVisible">
      <el-form :model="newItem">
        <el-form-item label="内容类型">
          <el-select v-model="newItem.linkType" filterable placeholder="挂载内容类型" @change="changeNewItemLinkType(newItem.linkType)">
            <el-option
              v-for="(type, index) in typeList"
              :key="index"
              :label="type.text"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="newItem.linkType === 'basicConfig' || newItem.linkType === 'contentConfig'" label="是否新增">
          <el-switch
            v-model="newItem.isNew"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <div v-if="!newItem.isNew">
          <template v-if="newItem.linkType === 'news'">
            <el-form-item v-for="(type, _index) in activeTypeList('newsType')" :key="'newsType_'+_index" label="资讯类型">
              <el-select v-model="item.newsType" filterable placeholder="资讯类型内容">
                <el-option
                  v-for="(link, index) in links[type.ref]"
                  :key="'nt_'+index"
                  :label="link.name"
                  :value="link.id"
                />
              </el-select>
            </el-form-item>
          </template>
          <el-form-item v-for="(type, _index) in activeTypeList(newItem.linkType, newItem.newsType)" :key="'link'+_index" label="挂载内容">
            <el-select v-model="newItem.link" filterable placeholder="详情">
              <el-option
                v-for="(link, index) in links[type.ref]"
                :key="index"
                :label="link.name"
                :value="link.id"
              />
            </el-select>
          </el-form-item>
          <template v-if="newItem.linkType === 'newsType'" class="text item">
            <el-form-item label="资讯板块标题">
              <el-input v-model="newItem.value" />
            </el-form-item>
          </template>
        </div>
        <div v-else>
          <div v-if="newItem.linkType === 'basicConfig'">
            <basic-config ref="basicConfig" :form="newItem.basicConfig" @saveBasicConfigSuccess="saveBasicConfigSuccess" />
          </div>
          <div v-if="newItem.linkType === 'contentConfig'">
            <content-config ref="contentConfig" :form="newItem.contentConfig" @saveContentConfigSuccess="saveContentConfigSuccess" />
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getByCode, postData } from '@/api/basicConfig/index'
import Sticky from 'components/Sticky'
import basicConfig from './basicConfig'
import ContentConfig from './content'
import { getVocationalLink, getAllNewsTypeLink, getNewsLink, getNewsLinkByType, getBasicConfigLink, getContentConfigLink, getAlbumsLink } from '@/api/common'

const typeList = [
  { value: 'newsType', text: '类型', hasId: true, input: false, ref: 'newsTypeLink', routerLink: '/news/detail?type={id}&tab=1' },
  { value: 'basicConfig', text: '条目内容', hasId: true, input: false, ref: 'basicConfigLink', routerLink: '/others/basicConfig?id={id}&tab=3' },
  { value: 'contentConfig', text: '段落内容', hasId: true, input: false, ref: 'contentConfigLink', routerLink: '/others/contentConfig?id={id}&tab=3' },
  { value: 'albumConfig', text: '相册', hasId: true, input: false, ref: 'albumLink', routerLink: '/photo/index?id={id}&tab=3' }
]

const nTypeList = [
  { value: 'newsType', text: '类型', hasId: true, input: false, ref: 'newsTypeLink', routerLink: '/news/detail?type={id}&tab=1' },
  { value: 'basicConfig', text: '条目内容', hasId: true, input: false, ref: 'basicConfigLink', routerLink: '/others/basicConfig?id={id}&tab=3' },
  { value: 'albumConfig', text: '相册', hasId: true, input: false, ref: 'albumLink', routerLink: '/photo/index?id={id}&tab=3' }
]

export default {
  name: 'Index',
  components: { ContentConfig, Sticky, basicConfig },
  props: {
    code: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    },
    position: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      form: {
        classifyCode: this.code,
        classifyName: this.name,
        status: 'up',
        basicItems: []
      },
      newItem: {
        isNew: false,
        basicConfig: {
          classifyName: '',
          classifyCode: '',
          basicItems: [{
            code: '',
            name: '',
            value: '',
            valueType: 'text',
            link: '',
            linkType: '',
            newsType: '',
            imgData: {
              myId: Math.random(),
              path: 'category',
              imgUrl: '',
              ImgSize: 10000,
              text: '图片大小不得超过10000K，支持png/jpg格式'
            }
          }]
        },
        contentConfig: {
          code: '',
          name: '',
          value: ''
        }
      },
      dialogFormVisible: false,
      basicItems: [],
      typeList: this.position === 'home-right' ? typeList: nTypeList,
      links: {
        basicConfigLink: [],
        newsTypeLink: [],
        contentConfigLink: []
      },
      ajaxStatus: false
    }
  },
  computed: {
    activeTypeList() {
      return (value, newsType) => {
        if (value === 'news' && newsType) {
          return [{ ref: `news-${newsType}` }]
        }
        return typeList.filter(type => type.value === value && type.hasId)
      }
    }
  },
  created() {
    getByCode(this.code).then(res => {
      const { data } = res
      if (!data) {
        return
      }
      this.form = Object.assign(this.form, data)
      const basicItems = JSON.parse(JSON.stringify(this.form.basicItems))
      basicItems.forEach(e => {
        e.imgData = {
          myId: Math.random(),
          path: 'category',
          imgUrl: e.value,
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        }
        e.imgData2 = {
          myId: Math.random(),
          path: 'category',
          imgUrl: e.phoneImg,
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        }
        e.videoContent = ''
      })
      this.basicItems = basicItems
    })
    this.getLinkData()
  },
  methods: {
    getLinkData() {
      getVocationalLink()
        .then(data => {
          this.links.vocationalLink = data.data.content
        })
      getAllNewsTypeLink()
        .then(data => {
          this.links = Object.assign(this.links)
          this.links.newsTypeLink = data.data
          this.links.newsTypeLink.forEach(type => {
            getNewsLinkByType(type.name)
              .then(ndata => {
                this.links = Object.assign(this.links)
                this.links[`news-${type.id}`] = ndata.data.content.map(item => {
                  return {
                    ...item,
                    name: item.title
                  }
                })
              })
          })
        })
      getNewsLink().then(data => {
        this.links = Object.assign(this.links)
        this.links.newsLink = data.data.content.map(item => {
          return {
            ...item,
            name: item.title
          }
        })
      })
      getBasicConfigLink().then(res => {
        const { data } = res
        this.links = Object.assign(this.links)
        this.links.basicConfigLink = data.map(item => {
          return {
            ...item,
            name: item.classifyName
          }
        })
      })
      getContentConfigLink().then(res => {
        const { data } = res
        this.links = Object.assign(this.links)
        this.links.contentConfigLink = data
      })
      getAlbumsLink().then(res => {
        const { data } = res
        this.links = Object.assign(this.links)
        this.links.albumLink = data
      })
    },
    changeNewItemLinkType(linkType) {
      this.newItem.isNew = false
    },
    confirmDialog() {
      if (!this.newItem.isNew) {
        this.basicItems.push({
          code: 'home-left-' + this.basicItems.length,
          name: '左侧-' + this.basicItems.length,
          value: this.newItem.value,
          link: this.newItem.link,
          linkType: this.newItem.linkType,
          valueType: 'text',
          imgData: {
            myId: Math.random(),
            path: 'category',
            imgUrl: '',
            ImgSize: 10000,
            text: '图片大小不得超过10000K，支持png/jpg格式'
          }
        })
        this.dialogFormVisible = false
      } else if (this.newItem.linkType === 'basicConfig') {
        this.saveBasicConfig()
      } else if (this.newItem.linkType === 'contentConfig') {
        this.saveContentConfig()
      }
    },
    addCard() {
      // const index = this.basicItems.length + 1
      this.dialogFormVisible = true
    },
    deletCard(idx) {
      this.basicItems.splice(idx, 1)
    },
    saveBasicConfig() {
      if (this.$refs.basicConfig) {
        this.$refs.basicConfig.submitForm('up')
      }
    },
    saveContentConfig() {
      if (this.$refs.contentConfig) {
        this.$refs.contentConfig.submitForm('up')
      }
    },
    /**
       * 保存、发布接口
       *
       * id：保存为空，编辑传列表id
       */
    submitForm(status) {
      if (this.ajaxStatus) {
        return
      }
      this.ajaxStatus = true

      const errorText = this.validateForm()
      if (errorText) {
        this.ajaxStatus = false
        this.$message.error(errorText)
        return
      }
      this.form.basicItems = this.basicItems
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.status = status
          postData(this.form)
            .then(re => {
              this.ajaxStatus = false
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.reset()
            })
            .catch(() => {
              this.ajaxStatus = false
            })
        } else {
          this.ajaxStatus = false
          this.$message.error('请正确填写完整信息后再发布')
          return false
        }
      })
    },

    resetActivityType(idx) {
      this.$set(this.basicItems[idx], 'detailLink', '')
      this.$set(this.basicItems[idx], 'buyLink', [{
        name: '',
        buyPlatformColor: '#000',
        link: ''
      }])
    },
    /**
       * 验证表单项
       * @returns {string} 错误提示
       */
    validateForm() {
      this.basicItems.forEach(item => {
        if (item.valueType === 'image') {
          item.value = item.imgData.imgUrl
        }
      })
      return ''
    },
    goToDetail(item) {
      console.log('item is ', item)
      const path = typeList.find(next => next.value === item.linkType)
      if (path) {
        this.$router.push({
          path: path.routerLink.replace('{id}', item.link)
        })
      }
    },
    saveContentConfigSuccess(content) {
      this.newItem.isNew = false
      this.newItem.link = content.id
      this.links.contentConfigLink.push(content)
      this.confirmDialog()
    },
    saveBasicConfigSuccess(props) {
      this.newItem.isNew = false
      this.newItem.link = props.id
      this.links.basicConfigLink.push(props)
      this.confirmDialog()
    }
  }
}
</script>

<style scoped lang="scss">
  .href-remark{
    color: #5e6d82;
    .red {
      background-color: #fdf6ec;
      color: #e6a23c;
    }
  }
  .logo-card{
    margin-bottom: 10px;
  }
  .video_upload_con{
    height: 100px;
    width: auto;
  }
</style>
